package com.example.its2021606134chh.ETCModule;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ETC_account_managementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ETC_account_managementFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView tvETCBalanceTitle;
    private TextView tvetcBalance;
    private TextView tvETCCarNumTitle;
    private Spinner spETCCarNum;
    private TextView tvETCRechargeNumTitle;
    private EditText edtETCRechargeNum;
    private Button btnETCSearch;
    private Button btnETCRecharge;
    MySQLiteOpenHelper openHelper;
    SQLiteDatabase database;

    public ETC_account_managementFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ETC_account_managementFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ETC_account_managementFragment newInstance(String param1, String param2) {
        ETC_account_managementFragment fragment = new ETC_account_managementFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_e_t_c_account_management, container, false);
        tvetcBalance = (TextView) view.findViewById(R.id.tvetcBalance);
        spETCCarNum = (Spinner) view.findViewById(R.id.spETCCarNum);
        edtETCRechargeNum = (EditText) view.findViewById(R.id.edtETCRechargeNum);
        btnETCSearch = (Button) view.findViewById(R.id.btnETCSearch);
        btnETCRecharge = (Button) view.findViewById(R.id.btnETCRecharge);
        // Inflate the layout for this fragment
//      创建数据库打开MySQLiteOpenHelper类
        openHelper = new MySQLiteOpenHelper(getContext(), "ETCaccount1.db", null, 1);

//        使用已构建好的HttpUtil类的asyncRequest()方法传入所需参数，根据返回值刷新余额
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                    @Override
                    public void onFailure(Exception e) {

                    }

                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        ETC_Car_Balance carBalance = gson.fromJson(json, ETC_Car_Balance.class);
                        tvetcBalance.setText(String.valueOf(carBalance.getBalance()));
                    }
                }, "get_car_account_balance", new String[]{"CarId", "UserName"}, 1, "user1");
            }
        }).start();

//        使用已构建好的HttpUtil类的asyncRequest()方法传入所需参数，根据返回值刷新余额
        btnETCSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int carNum = Integer.parseInt(spETCCarNum.getSelectedItem().toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                            @Override
                            public void onFailure(Exception e) {

                            }

                            @Override
                            public void onResponse(String json) {
                                Gson gson = new Gson();
                                ETC_Car_Balance carBalance = gson.fromJson(json, ETC_Car_Balance.class);
                                tvetcBalance.setText(String.valueOf(carBalance.getBalance()));
                            }
                        }, "get_car_account_balance", new String[]{"CarId", "UserName"}, carNum, "user1");
                    }
                }).start();
            }
        });

//        根据Spinner的值传入所需参数，根据返回值刷新余额和录入数据库
        btnETCRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int carID = Integer.parseInt(spETCCarNum.getSelectedItem().toString());
                int carBalance = Integer.parseInt(tvetcBalance.getText().toString());
                int carRecharge = Integer.parseInt(edtETCRechargeNum.getText().toString());
//                取得当前时间
                Date dNow = new Date();
                SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
                String sNow = ft.format(dNow);

//                输入值检测
                if (carRecharge >= 1 && carRecharge <= 999) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                @Override
                                public void onFailure(Exception e) {

                                }

                                @Override
                                public void onResponse(String json) {
                                    Log.i("TAG", json);
                                    Gson gson = new Gson();
                                    ETC_Car_Recharge car_recharge = gson.fromJson(json, ETC_Car_Recharge.class);
                                    String RESULT = car_recharge.getRESULT();
                                    if (RESULT.equals("S")) {
                                        Toast.makeText(getActivity(), "充值成功", Toast.LENGTH_SHORT).show();
//                                    偷懒
                                        tvetcBalance.setText(String.valueOf(carBalance + carRecharge));

//                                        向数据库传入数据
                                        ContentValues values = new ContentValues();
                                        values.put("carID", carID);
                                        values.put("carBalance", carBalance + carRecharge);
                                        values.put("carRecharge",carRecharge);
                                        values.put("user", "user1");
                                        values.put("time", sNow);
                                        database = openHelper.getWritableDatabase();
                                        database.insert("etccar", null, values);
                                        database.close();
                                    }
                                }
                            }, "set_car_account_recharge", new String[]{"CarId", "Money", "UserName"}, carID, carRecharge, "user1");
                        }
                    }).start();
                } else {
                    Toast.makeText(getActivity(), "只能输入1到999之间的整数", Toast.LENGTH_SHORT).show();
                }
            }
        });

        return view;
    }

    private void initView() {

    }
}